<template>
  <div class="small-login">
    <small-poup ref="signSuccess" type="bottom" v-show="showPopup">
      <div class="small-login-pop-cont">
        <!-- TODO 暂时隐藏授权弹框图片 -->
        <div class="small-login-pop-cont-top">
          <div class="small-shop-img"><img :src="accountInfo.icon" alt=""></div>
          <div class="small-shop-name"><span>{{accountInfo.nickname}}</span></div>
        </div>
        <div class="small-login-pop-cont-msg">
          <div class="small-shop-msg">为了更好为您服务，请点击授权</div>
            <div class="small-shop-tip" v-if="isAgreement.register_agreement || isAgreement.privacy_agreement">
            <div class="agreementChecked">
            <van-checkbox
              v-model="agreementChecked"
              icon-size="16px"
              checked-color="#F30C23"
            >
            </van-checkbox>
            </div>
            <div class="agreement-content">
              我已阅读并同意
              <template v-if="isAgreement.register_agreement"><span @click="handleLinkTo('userAgreement')">《用户服务协议》</span></template>
              <template v-if="isAgreement.register_agreement && isAgreement.privacy_agreement ">、</template>
              <span v-if="isAgreement.privacy_agreement" @click="handleLinkTo('privacyAgreement')">《个人隐私协议》</span>
            </div>
          </div>
        </div>

        <div class="small-login-pop-cont-btn">
          <div class="small-login-btn-item" @click="cancleBtn"><wx-button>取消</wx-button></div>
          <div class="small-login-btn-item">
            <small-button v-if="canIUseGetUserProfile" @NewGetUserProfile="NewGetUserProfile"></small-button> 
            <wx-button v-else @click="BindGetUserInfo" open-type="getUserInfo">授权</wx-button>
          </div>
        </div>
      </div>
    </small-poup>
    <div class="loadingx" @touchmove.prevent v-if="loading">
      <div class="loadingx-wrap">
        <div class="loadingx-wrap-shade"></div>
        <div class="loadingx-wrap-img">
          <img src="https://img.wifenxiao.com/h5-wfx/images/public/loading3.gif" alt />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Checkbox } from 'vant'

Vue.use(Checkbox)
import SmallPoup from '../smallPoup/index.vue'
import small from '@/smallapp/small'
import { wxLoginByCode } from '@/api/small/login'
import { bindSuperior } from '@/api/login'
import { wxKfUserInfo } from '@/api/small/common'
import { openPage } from '@/utils/utils'
import wxStoreage from '@/smallApp/storage'

export default Vue.extend({
  components: {
    SmallPoup,
  },
  props: {
    dzShowPop: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showPopup: false,
      canIUseGetUserProfile: false,
      loading: false,
      accountInfo: {},
      agreementChecked: false,
      isAgreement: {
        register_agreement: 0,
        privacy_agreement: 0
      }
    }
  },
  created() {
    this.isAgreement = small.wxCache('isAgreement')
  },
  mounted() {
    this.accountInfo = __wxConfig.accountInfo
    if ((wxStoreage.wxCache('small_check_unionid') == 1) || (this.dzShowPop)) {
      this.isAgreement = small.wxCache('isAgreement')
      this.showPopup = true
    }
    this.$Bus.$on('commonConfig', (res) => {
      if(res.data.small_check_unionid) { //开启强制授权
        this.isAgreement = small.wxCache('isAgreement')
        this.showPopup = true
      } else if(this.dzShowPop) {
        this.isAgreement = small.wxCache('isAgreement')
        this.showPopup = true
      } else {
        this.showPopup = false
      }
    })
  },
  methods: {
    handleLinkTo(url, data) {
      this.$JumpName(this, url, data)
    },
    openSmallLoginPop() {
      if (small.wxCache('isTimelineOut') && small.wxCache('isTimelineOut') == 1) {
        return false
      }
      if (wx.getUserProfile) { // 兼容新版授权模式，如果支持就进行新方法使用
        this.isAgreement = small.wxCache('isAgreement')
        // this.showPopup = true
        // if ((wxStoreage.wxCache('small_check_unionid') == 1) || (this.dzShowPop)) {
        //   this.isAgreement = small.wxCache('isAgreement')
        //   this.showPopup = true
        // }
        // this.$Bus.$on('commonConfig', (res) => {
        //   if(res.data.small_check_unionid) { //开启强制授权
        //     this.isAgreement = small.wxCache('isAgreement')
        //     this.showPopup = true
        //   } else if(this.dzShowPop) {
        //     this.isAgreement = small.wxCache('isAgreement')
        //     this.showPopup = true
        //   } else {
        //     this.showPopup = false
        //   }
        // })
        this.showPopup = true
        // console.log('支持最新方法')
        this.canIUseGetUserProfile = true
      } else {
        // console.log('不支持最新方法')
      }
      this.$refs.signSuccess.open()
    },
    BindGetUserInfo() {
      if ((this.isAgreement.register_agreement || this.isAgreement.privacy_agreement) && !this.agreementChecked) {
        this.$Error('请阅读并勾选协议')
      } else {
        this.wxLogin()
      }
    },
    wxLogin() {
      this.loading = true
      wx.login({
        success: (res) => {
          wx.getUserInfo({
            withCredentials: true,
            lang: 'zh_CN',
            success: (res2) => {
              let userlogin = {}
              let globalLoginInfo = {}
              globalLoginInfo.uid = '0'
              globalLoginInfo.token = '0'
              userlogin = res2.userInfo
              small.wxCache('userlogin', userlogin, 2592000)
              // small.wxCache('global_login_info', globalLoginInfo, 2592000)
              const sendData = {}
              sendData.code = res.code
              sendData.iv = res2.iv
              sendData.encryptedData = res2.encryptedData
              if (small.wxCache('pid')) {
                sendData.bpid = small.wxCache('pid')
                sendData.origin = small.wxCache('pathUrl')
              }
              if (small.wxCache('dptrace')) {
                sendData.dptrace = small.wxCache('dptrace')
              }
              // console.log(small.wxCache('ZB_PARAMS'), '取到的值')
              if (small.wxCache('ZB_PARAMS')) { // 直播分享直播间绑定上下级注册参数，修改时请注意
                const zb = small.wxCache('ZB_PARAMS')
                sendData.zb = JSON.stringify(zb)
              }
              wxLoginByCode(sendData).then((resc) => {
                this.loading = false
                // console.log(sendData, '请求传输的值')
                if (resc.status == 1) {
                  this.$Error('授权成功')
                  globalLoginInfo = resc.data
                  this.wxKfUserInfoFun()
                  small.wxCache('global_login_info', globalLoginInfo, 2592000)
                  if (small.wxCache('pid')) { // 如果可以取到上级pid进行绑定上下级操作
                    // 绑定上下级方法
                    bindSuperior({ bpid: small.wxCache('pid'), origin: small.wxCache('pathUrl') }).then((res) => { 
                      // console.log(res)
                    })
                  }
                  window.$$publish('loginReload', true)
                  this.cancleBtn()
                } else {
                  wx.clearStorageSync()

                  if (resc.data.redirect_url) {
                    // 当需要推荐人的时候进行页面跳转
                    openPage(resc.data.redirect_url)
                  } else {
                    this.$Error(resc.msg)
                  }
                }
              })
            },
            fail: () => {
              this.loading = false
              this.$Error('授权失败，请先允许获取你的昵称、头像')
              wx.openSetting({
                success(resp) {
                  // console.log(resp)
                }
              })
            }
          })
        },
        fail: () => {
          this.loading = false
          this.$Error('授权失败，请重试')
        }
      })
    },
    NewGetUserProfile() {
      if ((this.isAgreement.register_agreement || this.isAgreement.privacy_agreement) && !this.agreementChecked) {
        this.$Error('请阅读并勾选协议')
      } else {
        this.newWxLogin()
      }
    },
    newWxLogin() {
      this.loading = true
      wx.getUserProfile({
        desc: '用于完善会员资料',
        lang: 'zh_CN',
        success: (res2) => {
          wx.login({
            success: (res) => {
              let userlogin = {}
              let globalLoginInfo = {}
              globalLoginInfo.uid = '0'
              globalLoginInfo.token = '0'
              userlogin = res2.userInfo
              small.wxCache('userlogin', userlogin, 2592000)
              // small.wxCache('global_login_info', globalLoginInfo, 2592000)
              const sendData = {}
              sendData.code = res.code
              sendData.iv = res2.iv
              sendData.encryptedData = res2.encryptedData
              sendData.nickname = res2.userInfo ? res2.userInfo.nickName : undefined
              sendData.headimgurl = res2.userInfo ? res2.userInfo.avatarUrl : undefined
              if (small.wxCache('pid')) {
                sendData.bpid = small.wxCache('pid')
                sendData.origin = small.wxCache('pathUrl')
              }
              if (small.wxCache('dptrace')) {
                sendData.dptrace = small.wxCache('dptrace')
              }
              // console.log(small.wxCache('ZB_PARAMS'), '取到的值')
              if (small.wxCache('ZB_PARAMS')) { // 直播分享直播间绑定上下级注册参数，修改时请注意
                const zb = small.wxCache('ZB_PARAMS')
                sendData.zb = JSON.stringify(zb)
              }
              wxLoginByCode(sendData).then((resc) => {
                this.loading = false
                // console.log(sendData, '请求传输的值')
                if (resc.status == 1) {
                  this.$Error('授权成功')
                  globalLoginInfo = resc.data
                  this.wxKfUserInfoFun()
                  small.wxCache('global_login_info', globalLoginInfo, 2592000)
                  if (small.wxCache('pid')) { // 如果可以取到上级pid进行绑定上下级操作
                    // 绑定上下级方法
                    bindSuperior({ bpid: small.wxCache('pid'), origin: small.wxCache('pathUrl') }).then((res) => { 
                      // console.log(res)
                    })
                  }
                  window.$$publish('loginReload', true)
                  this.cancleBtn()
                } else {
                  wx.clearStorageSync()

                  if (resc.data.redirect_url) {
                    // 当需要推荐人的时候进行页面跳转
                    openPage(resc.data.redirect_url)
                  } else {
                    this.$Error(resc.msg)
                  }
                }
              })
            },
            fail: (rep) => {
              // console.log('失败了', rep)
              this.loading = false
              this.$Error('授权失败，请先允许获取你的昵称、头像')
              wx.openSetting({
                success(resp) {
                  // console.log(resp)
                }
              })
            }
          })
        },
        fail: (rep) => {
          // console.log('失败了', rep)
          this.loading = false
          this.$Error('授权失败，请先允许获取你的昵称、头像')
          wx.openSetting({
            success(resp) {
              // console.log(resp)
            }
          })
        }
      })
    },
    wxKfUserInfoFun() {
      wxKfUserInfo().then((res) => {
        if (res.status == 1) {
          small.wxCache('kfUserInfo', res.data, 2592000)
        }
      })
    },
    cancleBtn() {
      this.$refs.signSuccess.close()
    }
  },
  beforeDestroy() {
    this.$Bus.$off('commonConfig')
  }
})
</script>

<style lang="scss">
  .small-login {
    background: #fff;
    position: relative;
    &-pop {
      overflow:hidden;
      border-radius:20px 20px 0 0;
      &-cont {
        padding: 60px 50px;
        &-top {
          margin-bottom: 45px;
          display: flex;
          flex-direction: row;
          align-items: center;
          .small-shop-img {
            width: 68px;
            height: 68px;
            border-radius: 50%;
            margin-right: 15px;
            overflow: hidden;
            img {
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
          .small-shop-name {
            font-size: 26px;
            font-weight: bold;
          }
        }
        &-msg {
          margin-bottom: 60px;
          .small-shop-msg {
            font-size:32px;
            font-weight:bold;
            color:rgba(51,51,51,1);
            margin-bottom: 21px;
          }
          .small-shop-tip {
            display: flex;
            align-items: baseline;
            font-size: 24px;
            font-weight:500;
            margin-top: 40px;
            .agreementChecked {
              position: relative;
              top: 10px;
            }
            .agreement-content {
              color:rgba(102,102,102,1);
              line-height: 36px;
              margin-left: 20px;
              position: relative;
              top:6px;
            }
            span {
              color:rgba(255,0,0,1);
            }
          }
        }
        &-btn {
          display: flex;
          flex-direction: row;
          flex-wrap: nowrap;
          justify-content: space-around;
          .small-login-btn-item {
            width:196px;
            height:76px;
            font-size: 28px;
            line-height: 76px;
            border:1px solid rgba(255,0,0,1);
            border-radius:8px;
            text-align: center;
            color: rgba(255,0,0,1);
            &:last-child {
              background-color: rgba(255,0,0,1);
              color: #fff;
            }
          }
        }
      }
    }
  }
  .loadingx {
    position: fixed;
    z-index: 999999;
    height: 100vh;
    width: 100%;
    top: 0;
    left: 0;
    background: rgba(0,0,0,0.3);
    &-wrap {
      height: 100%;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      &-shade {
        position: absolute;
        z-index: 1;
        width: 100%;
        height: 100%;
        /*background: rgba(0,0,0,.1);*/
      }
      &-app {
        position: relative;
        z-index: 2;
        color: #fff;
      }
      &-img {
        img {
          width: 120px;
        }
      }
    }
  }
</style>
